/**
 * 通知设置管理器
 * 管理应用的通知行为设置
 */

import settingsStorage from './storage.js'

class NotificationSettings {
  constructor() {
    this.storageKey = 'notification'
    this.defaultSettings = {
      enabled: true,                    // 推送通知总开关
      messageNotification: true,        // 消息通知
      friendRequestNotification: true,  // 好友请求通知
      systemNotification: true,         // 系统通知
      sound: true,                      // 声音提醒
      vibration: true,                  // 震动提醒
      doNotDisturb: false,             // 免打扰模式
      doNotDisturbStart: '22:00',      // 免打扰开始时间
      doNotDisturbEnd: '08:00'         // 免打扰结束时间
    }
    
    // 加载设置
    this.settings = this.loadSettings()
    
    console.log('[NotificationSettings] 初始化完成')
  }
  
  /**
   * 加载设置
   * @returns {Object} 设置对象
   */
  loadSettings() {
    const saved = settingsStorage.load(this.storageKey, null)
    
    if (saved) {
      // 合并默认设置和已保存的设置（确保新增的设置项有默认值）
      return { ...this.defaultSettings, ...saved }
    }
    
    return { ...this.defaultSettings }
  }
  
  /**
   * 获取当前设置
   * @returns {Object} 设置对象
   */
  getSettings() {
    return { ...this.settings }
  }
  
  /**
   * 保存设置
   * @param {Object} settings - 设置对象
   * @returns {Boolean} 是否保存成功
   */
  saveSettings(settings) {
    try {
      this.settings = { ...this.settings, ...settings }
      const success = settingsStorage.save(this.storageKey, this.settings)
      
      if (success) {
        console.log('[NotificationSettings] 设置已保存:', this.settings)
      }
      
      return success
    } catch (error) {
      console.error('[NotificationSettings] 保存设置失败:', error)
      return false
    }
  }
  
  /**
   * 更新单个设置项
   * @param {String} key - 设置键名
   * @param {*} value - 设置值
   * @returns {Boolean} 是否更新成功
   */
  updateSetting(key, value) {
    if (!(key in this.settings)) {
      console.warn(`[NotificationSettings] 未知的设置项: ${key}`)
      return false
    }
    
    this.settings[key] = value
    return this.saveSettings(this.settings)
  }
  
  /**
   * 重置为默认值
   * @returns {Boolean} 是否重置成功
   */
  reset() {
    this.settings = { ...this.defaultSettings }
    const success = settingsStorage.save(this.storageKey, this.settings)
    
    if (success) {
      console.log('[NotificationSettings] 设置已重置为默认值')
    }
    
    return success
  }
  
  /**
   * 检查是否在免打扰时间段
   * @returns {Boolean} 是否在免打扰时间段
   */
  isInDoNotDisturbPeriod() {
    if (!this.settings.doNotDisturb) {
      return false
    }
    
    try {
      const now = new Date()
      const currentTime = now.getHours() * 60 + now.getMinutes()
      
      const [startHour, startMinute] = this.settings.doNotDisturbStart.split(':').map(Number)
      const [endHour, endMinute] = this.settings.doNotDisturbEnd.split(':').map(Number)
      
      const startTime = startHour * 60 + startMinute
      const endTime = endHour * 60 + endMinute
      
      // 处理跨天的情况（如22:00-08:00）
      if (startTime > endTime) {
        return currentTime >= startTime || currentTime < endTime
      } else {
        return currentTime >= startTime && currentTime < endTime
      }
    } catch (error) {
      console.error('[NotificationSettings] 判断免打扰时间段失败:', error)
      return false
    }
  }
  
  /**
   * 检查是否应该显示通知
   * @param {String} type - 通知类型 (message/friendRequest/system)
   * @returns {Boolean} 是否应该显示通知
   */
  shouldShowNotification(type) {
    // 检查总开关
    if (!this.settings.enabled) {
      console.log('[NotificationSettings] 通知总开关已关闭')
      return false
    }
    
    // 检查免打扰模式
    if (this.isInDoNotDisturbPeriod()) {
      console.log('[NotificationSettings] 当前处于免打扰时间段')
      return false
    }
    
    // 检查具体类型的开关
    switch (type) {
      case 'message':
        return this.settings.messageNotification
      case 'friendRequest':
        return this.settings.friendRequestNotification
      case 'system':
        return this.settings.systemNotification
      default:
        console.warn(`[NotificationSettings] 未知的通知类型: ${type}`)
        return true
    }
  }
  
  /**
   * 检查是否启用声音提醒
   * @returns {Boolean} 是否启用声音
   */
  isSoundEnabled() {
    return this.settings.enabled && this.settings.sound && !this.isInDoNotDisturbPeriod()
  }
  
  /**
   * 检查是否启用震动提醒
   * @returns {Boolean} 是否启用震动
   */
  isVibrationEnabled() {
    return this.settings.enabled && this.settings.vibration && !this.isInDoNotDisturbPeriod()
  }
  
  /**
   * 获取免打扰状态描述
   * @returns {String} 状态描述
   */
  getDoNotDisturbStatus() {
    if (!this.settings.doNotDisturb) {
      return '已关闭'
    }
    
    if (this.isInDoNotDisturbPeriod()) {
      return `生效中 (${this.settings.doNotDisturbStart}-${this.settings.doNotDisturbEnd})`
    }
    
    return `已设置 (${this.settings.doNotDisturbStart}-${this.settings.doNotDisturbEnd})`
  }
}

// 导出单例
export default new NotificationSettings()
